package com.xrit.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.constant.MessageConstant;
import com.xrit.constant.RedisMessageConstant;
import com.xrit.exception.CustomException;
import com.xrit.pojo.SetMeal;
import com.xrit.utils.QiNiuUtils;
import com.xrit.query.QueryPageBean;
import com.xrit.result.PageResult;
import com.xrit.result.Result;
import com.xrit.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("setMeal")
public class SetMealController {

    @Reference
    private SetMealService setMealService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 删除套餐
     * @param id
     * @return
     * @throws CustomException
     */
    @PostMapping("/deleteById")
    public Result deleteById(Integer id,String img) throws CustomException {
        //1.删除套餐
        setMealService.deleteById(id);
        if (!StringUtils.isEmpty(img)){
            //2.七牛云删除图片
            QiNiuUtils.removeFiles(img);
            //3.redis移除这个被删除的图片
            jedisPool.getResource().srem(RedisMessageConstant.SETMEAL_PIC_DB_RESOURCES,img);
        }
        return new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS);
    }

    /**
     * 修改
     * @param meal
     * @param checkgroupIds
     * @return
     */
    @PostMapping("update")
    public Result update(@RequestBody SetMeal meal,Integer [] checkgroupIds) {
        try{
            //1.更新检查组
            setMealService.update(meal, checkgroupIds);
            //2.判断图片是否有更改
            SetMeal byId = setMealService.findDetailsById(meal.getId());

            if (!StringUtils.isEmpty(meal.getId())
                    && !StringUtils.isEmpty(byId.getImg())
                    && !meal.getImg().equals(byId.getImg())){
                //2.1 有新的图片的话，旧的图片就不需要了，就要删除掉
                jedisPool.getResource().srem(RedisMessageConstant.SETMEAL_PIC_DB_RESOURCES,byId.getImg());
            }
            //3.修改成功，要记录有用的图片到redis集合中
            jedisPool.getResource().sadd(RedisMessageConstant.SETMEAL_PIC_DB_RESOURCES, meal.getImg());
            return new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true,MessageConstant.EDIT_SETMEAL_FAIL);
        }
    }

    /**
     * 查询套餐信息
     * @param id
     * @return
     */
    @RequestMapping("/findById.do")
    public Result findById(Integer id){
        SetMeal meal = setMealService.findDetailsById(id);
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("domain",QiNiuUtils.DOMAIN);
        map.put("setMeal",meal);
        return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,map);
    }

    /**
     * 查询套餐包含的检查组
     * @param id
     * @return
     */
    @RequestMapping("/findCheckGroupByMealId.do")
    public Result findCheckGroupByMealId(Integer id){
        try{
            List<Integer> list = setMealService.findCheckGroupByMealId(id);
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    //文件上传
    @RequestMapping("/upload.do")
    public Result upload(MultipartFile  imgFile){
        try {
            if (imgFile!=null && !imgFile.isEmpty()){
                //1.获取原始图片的名称
                String originalFilename = imgFile.getOriginalFilename();
                //2.使用uuid创建新的文件
                String newName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

                //3.使用七牛云进行文件上传
                QiNiuUtils.uploadViaByte(imgFile.getBytes(),newName);

                /**
                 * 4.返回数据给页面
                 * data:{domain:'',imgName:''}
                 */
                Map<String,String> map=new HashMap<>();
                map.put("domain",QiNiuUtils.DOMAIN);
                map.put("imgName",newName);

                //5.将上传的图片名称保存到数据中(基于set集合的)
                jedisPool.getResource().sadd(RedisMessageConstant.SETMEAL_PIC_RESOURCES,newName);

                return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,map);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
    }


    /**
     * 添加套餐
     * @param setMeal
     * @param checkgroupIds
     * @return
     */
    @RequestMapping("/add.do")
    public Result add(@RequestBody SetMeal setMeal,Integer [] checkgroupIds){
        //1.添加套餐基础数据以及套餐与检查组的关联数据
        setMealService.addSetMeal(setMeal,checkgroupIds);
        //2.添加成功，要记录有用的图片到数据库中
        Jedis resource = jedisPool.getResource();
        resource.sadd(RedisMessageConstant.SETMEAL_PIC_DB_RESOURCES,setMeal.getImg());
        resource.close();
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 分页条件查询
     */
    @RequestMapping("/findPage.do")
    public Result findAll(@RequestBody QueryPageBean queryPageBean){
        PageResult all = setMealService.findPage(queryPageBean);
        return new Result(true, all==null? MessageConstant.QUERY_CHECKGROUP_FAIL: MessageConstant.QUERY_CHECKGROUP_SUCCESS,all);
    }
}
